#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
真实HAI应用配置
基于实际的腾讯云HAI自定义应用信息
"""

from typing import Dict, List, Any

# 真实的HAI自定义应用信息
REAL_HAI_APPS = {
    "app-oefac6i2": {
        "app_id": "app-oefac6i2",
        "name": "GFPGAN API",
        "region": "ap-beijing",
        "status": "正常",
        "storage": "50 GB",
        "gpu_type": "basic",  # 根据成本优化策略选择最便宜的
        "endpoint": "https://app-oefac6i2.hai.tencentcloud.com",
        "description": "北京地域GFPGAN图像增强服务"
    },
    "app-d8orpkas": {
        "app_id": "app-d8orpkas", 
        "name": "GFPGAN API",
        "region": "ap-shanghai",
        "status": "正常",
        "storage": "50 GB",
        "gpu_type": "basic",
        "endpoint": "https://app-d8orpkas.hai.tencentcloud.com",
        "description": "上海地域GFPGAN图像增强服务"
    },
    "app-9diy38hx": {
        "app_id": "app-9diy38hx",
        "name": "GFPGAN API", 
        "region": "ap-guangzhou",
        "status": "正常",
        "storage": "50 GB",
        "gpu_type": "basic",
        "endpoint": "https://app-9diy38hx.hai.tencentcloud.com",
        "description": "广州地域GFPGAN图像增强服务"
    },
    "app-9qle417n": {
        "app_id": "app-9qle417n",
        "name": "GFPGAN API",
        "region": "ap-nanjing", 
        "status": "正常",
        "storage": "50 GB",
        "gpu_type": "basic",
        "endpoint": "https://app-9qle417n.hai.tencentcloud.com",
        "description": "南京地域GFPGAN图像增强服务"
    },
    "app-h5rw7hfh": {
        "app_id": "app-h5rw7hfh",
        "name": "GFPGAN API",
        "region": "ap-chongqing",
        "status": "正常", 
        "storage": "50 GB",
        "gpu_type": "basic",
        "endpoint": "https://app-h5rw7hfh.hai.tencentcloud.com",
        "description": "重庆地域GFPGAN图像增强服务"
    }
}

# 地域优先级配置（根据成本优化方案）
# 注意：ap-chengdu (成都) 不支持HAI服务，已移除
REGION_PRIORITY = [
    "ap-beijing",      # 北京 - app-oefac6i2
    "ap-nanjing",      # 南京 - app-9qle417n  
    "ap-guangzhou",    # 广州 - app-9diy38hx
    "ap-shanghai",     # 上海 - app-d8orpkas
    "ap-chongqing"     # 重庆 - app-h5rw7hfh
]

# 按地域分组的应用
APPS_BY_REGION = {
    "ap-beijing": ["app-oefac6i2"],
    "ap-nanjing": ["app-9qle417n"], 
    "ap-guangzhou": ["app-9diy38hx"],
    "ap-shanghai": ["app-d8orpkas"],
    "ap-chongqing": ["app-h5rw7hfh"]
    # 注意：ap-chengdu (成都) 不支持HAI服务
}

# 应用健康状态检查配置
HEALTH_CHECK_CONFIG = {
    "check_interval": 30,  # 30秒检查一次
    "timeout": 10,         # 10秒超时
    "max_retries": 3,      # 最大重试3次
    "healthy_threshold": 0.8,  # 80%成功率认为健康
    "endpoints": {
        app_id: app_info["endpoint"] + "/health"
        for app_id, app_info in REAL_HAI_APPS.items()
    }
}

# 负载均衡配置
LOAD_BALANCE_CONFIG = {
    "strategy": "round_robin",  # 轮询策略
    "health_check_enabled": True,
    "failover_enabled": True,
    "region_preference": REGION_PRIORITY,
    "max_concurrent_requests": 100,
    "request_timeout": 30
}

# 成本优化配置
COST_OPTIMIZATION_CONFIG = {
    "preferred_regions": REGION_PRIORITY,
    "gpu_type_preference": ["basic"],  # 优先使用最便宜的GPU类型
    "auto_scaling": {
        "enabled": True,
        "min_instances_per_region": 1,
        "max_instances_per_region": 3,
        "scale_up_threshold": 0.8,  # 80%负载时扩容
        "scale_down_threshold": 0.3  # 30%负载时缩容
    }
}

def get_app_info(app_id: str) -> Dict[str, Any]:
    """获取应用信息"""
    return REAL_HAI_APPS.get(app_id, {})

def get_apps_by_region(region: str) -> List[str]:
    """获取指定地域的应用列表"""
    return APPS_BY_REGION.get(region, [])

def get_available_apps() -> List[str]:
    """获取所有可用应用的ID列表"""
    return list(REAL_HAI_APPS.keys())

def get_healthy_apps() -> List[str]:
    """获取健康状态的应用ID列表"""
    return [
        app_id for app_id, app_info in REAL_HAI_APPS.items()
        if app_info.get("status") == "正常"
    ]

def get_app_endpoint(app_id: str) -> str:
    """获取应用端点"""
    app_info = get_app_info(app_id)
    return app_info.get("endpoint", "")

def get_region_for_app(app_id: str) -> str:
    """获取应用所属地域"""
    app_info = get_app_info(app_id)
    return app_info.get("region", "")

def get_preferred_app_for_region(region: str) -> str:
    """获取指定地域的优先应用"""
    apps = get_apps_by_region(region)
    if apps:
        return apps[0]  # 返回第一个可用应用
    return ""

def get_next_available_app(current_app_id: str = None) -> str:
    """获取下一个可用应用（负载均衡）"""
    healthy_apps = get_healthy_apps()
    
    if not healthy_apps:
        return ""
    
    if current_app_id and current_app_id in healthy_apps:
        current_index = healthy_apps.index(current_app_id)
        next_index = (current_index + 1) % len(healthy_apps)
        return healthy_apps[next_index]
    
    # 按地域优先级选择
    for region in REGION_PRIORITY:
        region_apps = get_apps_by_region(region)
        for app_id in region_apps:
            if app_id in healthy_apps:
                return app_id
    
    return healthy_apps[0]  # 默认返回第一个健康应用

def get_app_statistics() -> Dict[str, Any]:
    """获取应用统计信息"""
    total_apps = len(REAL_HAI_APPS)
    healthy_apps = len(get_healthy_apps())
    
    region_stats = {}
    for region in REGION_PRIORITY:
        region_apps = get_apps_by_region(region)
        region_healthy = len([app for app in region_apps if app in get_healthy_apps()])
        region_stats[region] = {
            "total": len(region_apps),
            "healthy": region_healthy,
            "apps": region_apps
        }
    
    return {
        "total_apps": total_apps,
        "healthy_apps": healthy_apps,
        "health_rate": healthy_apps / total_apps if total_apps > 0 else 0,
        "region_statistics": region_stats,
        "available_regions": [region for region, apps in APPS_BY_REGION.items() if apps]
    }

if __name__ == "__main__":
    # 测试配置
    print("=== 真实HAI应用配置测试 ===")
    
    # 显示所有应用
    print("\n所有应用:")
    for app_id, info in REAL_HAI_APPS.items():
        print(f"  {app_id}: {info['name']} ({info['region']}) - {info['status']}")
    
    # 显示地域优先级
    print(f"\n地域优先级: {REGION_PRIORITY}")
    
    # 显示健康应用
    healthy_apps = get_healthy_apps()
    print(f"\n健康应用: {healthy_apps}")
    
    # 显示应用统计
    stats = get_app_statistics()
    print(f"\n应用统计: {stats}")
    
    # 测试负载均衡
    print("\n负载均衡测试:")
    current_app = ""
    for i in range(5):
        next_app = get_next_available_app(current_app)
        print(f"  请求 {i+1}: {next_app} ({get_region_for_app(next_app)})")
        current_app = next_app
